package com.derbysoft.ota.infrastructure.guice;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.Lifecycle;

import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Stage;

public abstract class Injectors {

	private static Logger logger = LoggerFactory.getLogger(Injectors.class);

	private static Injector injector;

	public static Injector initialize(Stage stage, Module... modules) {
		Environments.initialize();
		injector = Guice.createInjector(stage, modules);
		startLifeCycled(injector);
		return injector;
	}

	private static void startLifeCycled(Injector injector) {
		logger.info("Starting lifecycled instances...");

		Map<Key<?>, Binding<?>> bindings = injector.getBindings();

		for (Map.Entry<Key<?>, Binding<?>> entry : bindings.entrySet()) {
			Class<?> rawType = entry.getKey().getTypeLiteral().getRawType();
			if (Lifecycle.class.isAssignableFrom(rawType)) {
				Binding<?> value = entry.getValue();
				Lifecycle lifecycle = (Lifecycle) value.getProvider().get();
				lifecycle.start();
			}
		}

		logger.info("Started lifecycled instances successfully.");
	}

	public static Injector get() {
		return injector;
	}
}
